/**
Definition for a binary tree node. */
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    int level = 0;
    //该题深搜与广搜均可
    void dfs(TreeNode * node, vector<int> &nums, int step){   //深搜,并记录层数
        if(node==nullptr) return;
        if(step>level){
            nums.push_back(node->val);
            this->level++;
        }
        dfs(node->right,nums,step+1);
        dfs(node->left,nums,step+1);
        return;
    }
    //接下来是广搜解法
    queue<TreeNode*>Q;
    void bfs(TreeNode* root, vector<int>&nums){
        if(root==nullptr) return;
        Q.push(root);
        while(!Q.empty()){
            //记录当前层数中，拥有的节点数
            int size = Q.size();
            for(int i=0;i<size;i++){
                TreeNode* node = Q.front();
                Q.pop();
                if(i==size-1)
                    nums.push_back(node->val);

                if(node->right!=nullptr)
                    Q.push(node->right);
                if(node->left!=nullptr)
                    Q.push(node->left);
            }
        }
        return;
    }
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res = {};
        // dfs(root,res,1);
        bfs(root, res);
        return res;
    }
};